<template>
    <div id="pageSet">
        <div class="nameBox" v-show="true">
            <p class="attrTitle">页面名称：</p>
            <input type="text" id="pageName" name="pageName" class="textInput" v-model="pageName"
                :disabled="getPageInfo.pageType != 1">
        </div>
        <p class="attrTitle">上传图片：
            <span class="myTip" @mouseenter="showTip = true" @mouseleave="showTip = false">
                <img src="/magicflu/html/image/weform_tip.png" alt="">
                <span class="myText" v-if="getPageInfo.pageType == 1" v-show="showTip">
                    <div>图片大小：800x588(像素)</div>
                    <div>图片格式：.png或.jpg格式</div>
                    <div>图片说明：此图片用于产品在安装/升级过程中定时切换显示，形成轮播动画效果</div>
                    <img src="/magicflu/html/image/weform_square.png" alt="">
                </span>
                <span class="myText" v-show="showTip" v-else>
                    <div>图片大小：800x600(像素)</div>
                    <div>图片格式：bmp格式</div>
                    <div>图片说明：此图片用于产品安装界面背景图，图片风格参考系统默认图片，您可以将现有默认图片下载下来稍作调整再使用</div>
                    <img src="/magicflu/html/image/weform_square.png" alt="">
                </span>
            </span>
        </p>
        <div class="imgBox">
            <p>
                <img :src="getBackGroundImageURL" @error="nofind" />
                <span class="fileName" :title="getBgImgName">{{ getBgImgName }}</span>
            </p>
            <p>
                <span class="greyBtn"><input type="file" class="file" :accept="getInputAccept" multiple=""
                        @change="fileUpload($event, (getPageInfo.pageType == 1 ? 'slide' : 'bmp'))">上传图片</span>
                <a class="a_download" v-if="getPageInfo.pageType == 1" @click="choosePng($event)">选择图片</a>
                <!--<span class="greyBtn">删除图片</span>-->
                <a :href="downloadURL" target="_blank" class="a_download">下载图片</a>
            </p>
        </div>
        <div class="slideTimeBox" v-if="getPageInfo.pageType == 1">
            <p class="attrTitle">轮播时间：(单位：毫秒)</p>
            <input type="text" id="stayTime" name="stayTime" class="textInput" v-model="stayTime">
        </div>
        <div class="licenseBox" v-if="getPageInfo.pageType == 0">
            <p class="attrTitle">上传用户协议：<span class="greyBtn"><input type="file" class="file" accept=".rtf" multiple=""
                        @change="fileUpload($event, 'rtf')">选择文件</span></p>
            <span class="filespan">{{ decodeName(getPageInfo.license.name) }}</span>
            <span class="tagspan">注：用户协议以rtf格式结尾，可由txt文件更改后缀名生成</span>
        </div>

        <ModalItem ref="modal">
            <div id="slideListDiv">
                <ul id="slideListUL">
                    <li v-for="(item, index) in getSlideList" :key="index" @click="selectCurrentSlide(index)">
                        <div :class="{ 'slideDiv': true, 'slideDivActive': selectedIndex === index }">
                            <img :src="item.url">
                        </div>
                    </li>
                </ul>
            </div>
        </ModalItem>
    </div>
</template>
<script>
import packagingUtil from '../packagingUtil.js'
import ModalItem from '../components/ModalItem'
import ChooseSlidePng from '../pages/ChooseSlidePng'
export default {
    props: [''],
    components: { ModalItem, ChooseSlidePng },
    data() {
        return {
            action: 'product',
            showTip: false,
            selectedIndex: null
        }
    },
    mounted() {
        /*$("#pageSetForm").validate({
            rules: {
                pageName: {
                    required: true
                },
                stayTime: {
                    required: true,
                    digits: true
                }
            },
            messages: {
                pageName: {
                    required: "页面名称不能为空"
                },
                stayTime: {
                    required: "轮播时间不能为空",
                    digits: "轮播时间必须为数字且大于0"
                } 
            }
        });*/
    },
    methods: {
        selectCurrentSlide(index) {
            this.selectedIndex = index;
        },
        choosePng(event) {
            this.$store.commit("initSlides");
            this.selectedIndex = "";
            let self = this;
            this.$refs.modal.modalAlert({
                message: { slot: true },
                title: "选择轮播图",
                callback: () => {
                    let fileName = "系统轮播图" + (this.selectedIndex + 1) + ".png";
                    let imageUrl = "/magicflu/buildpackage/src/slidepng/slidePage_" + (this.selectedIndex + 1) + ".png";
                    self.getImageFileFromUrl(imageUrl, fileName).then((response) => {
                        // 返回的是文件对象，使用变量接收即可
                        let file = response;
                        let productId = self.$store.state.productInfo.id;
                        let spaceId = self.$store.state.spaceId;
                        let _activePageIndex = self.$store.state.activePageIndex;
                        let _activeOption = self.$store.state.activeOption;
                        let action = self.getAction(_activePageIndex, _activeOption);
                        let filename = self.$store.state.productInfo[_activeOption].pages.page[_activePageIndex].backgroundImage.nsisUseName;
                        let newfilename = filename;
                        let param = new FormData()
                        param.append('file', file, file.name)  // 通过append向form对象添加数据
                        let config = {
                            headers: { 'Content-Type': 'multipart/form-data' }
                        }
                        self.delFile(spaceId, productId, action, filename).then((res) => {
                            self.addFile(spaceId, productId, action, newfilename, file, param, config);
                        })
                        return false;
                    }).catch((e) => { console.error(e) })
                }
            });
        },
        fileUpload(event, fileType) {
            let productId = this.$store.state.productInfo.id;
            let spaceId = this.$store.state.spaceId;
            let _activePageIndex = this.$store.state.activePageIndex;
            let _activeOption = this.$store.state.activeOption;
            let action = this.getAction(_activePageIndex, _activeOption);
            let filename = this.$store.state.productInfo[_activeOption].pages.page[_activePageIndex].backgroundImage.nsisUseName;
            let self = this;
            let file = event.target.files[0];
            event.target.value = '';
            if (!file) {
                return false;
            }
            let param = new FormData()
            param.append('file', file, file.name)  // 通过append向form对象添加数据
            let config = {
                headers: { 'Content-Type': 'multipart/form-data' }
            }
            if (file.name.endsWith(".rtf")) {
                filename = this.$store.state.productInfo[_activeOption].pages.page[_activePageIndex].license.nsisUseName;
            }
            var pageType = this.$store.state.productInfo[_activeOption].pages.page[_activePageIndex].pageType;
            var oldName = filename.split(".")[0];
            var newNameExtension = file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length);
            var newfilename = filename;
            if (pageType == '1') {
                newfilename = oldName + "." + newNameExtension;
            }
            if (fileType == 'slide') {
                if (newNameExtension.toLowerCase() != 'png' && newNameExtension.toLowerCase() != 'jpg') {
                    packagingUtil.myAlert("轮播图片只支持png和jpg两种格式，且不能将其他格式图片重命名成png或jpg格式,否则图片将无法使用", "提示", this);
                    return false;
                }
            } else if (fileType == 'bmp') {
                if (newNameExtension.toLowerCase() != 'bmp') {
                    packagingUtil.myAlert("背景图只支持bmp格式，且不能将其他格式图片重命名成bmp格式,否则图片将无法使用", "提示", this);
                    return false;
                }
            } else if (fileType == 'rtf') {
                if (newNameExtension.toLowerCase() != 'rtf') {
                    packagingUtil.myAlert("用户协议只支持rtf格式，可由txt文件更改后缀名生成", "提示", this);
                    return false;
                }
            }
            this.delFile(spaceId, productId, action, filename).then((res) => {
                this.addFile(spaceId, productId, action, newfilename, file, param, config);
            })
        },
        addFile(spaceId, productId, action, filename, file, param, config) {
            var self = this;
            this.$axios.put('/magicflu/service/s/' + spaceId + '/packageres/' + productId + '/' + action + '/' + filename, param, config)
                .then(function (response) {
                    var tempObj = {
                        name: encodeURIComponent(file.name),
                        url: response.data,
                        nsisUseName: filename
                    }
                    if (file.name.endsWith(".rtf")) {
                        self.$store.commit('updateLicense', tempObj);
                    } else {
                        self.$store.commit('updateInstallOrUpgradePageResource', tempObj);
                    }
                }).catch(function (response) {
                    console.log(response)
                });
        },
        delFile(spaceId, productId, action, filename) {
            var self = this;
            return new Promise(function (resolve, reject) {
                self.$axios.delete('/magicflu/service/s/' + spaceId + '/packageres/' + productId + '/' + action + '/' + filename)
                    .then(function (response) {
                        resolve(response)
                    }).catch(function (response) {
                        //console.log(response)
                        resolve(response)
                    });
            })
        },
        getAction(activePageIndex, activeOption) {
            var pageType = '';
            var action = '';
            pageType = this.$store.state.productInfo[activeOption].pages.page[activePageIndex].pageType
            if (activeOption == 'installPage') {
                if (pageType == '1') {
                    action = 'install';
                } else {
                    action = 'product';
                }
            } else if (activeOption == 'upgradePage') {
                if (pageType == '1') {
                    action = 'upgrade';
                } else {
                    action = 'product';
                }
            }
            return action;
        },
        nofind() {
            var img = event.srcElement;
            img.src = "/magicflu/buildpackage/target/" + this.$store.state.spaceId + "/" + this.$store.state.productInfo.id + "/install-slides/slidePage_6.png";
            img.onerror = null; //控制不要一直跳动 
        },
        getImageFileFromUrl(url, imageName) {
            return new Promise((resolve, reject) => {
                var blob = null;
                var xhr = new XMLHttpRequest();
                xhr.open("GET", url);
                xhr.setRequestHeader('Accept', 'image/png');
                xhr.responseType = "blob";
                // 加载时处理
                xhr.onload = () => {
                    // 获取返回结果
                    blob = xhr.response;
                    let imgFile = new File([blob], imageName, { type: 'image/png' });
                    // 返回结果
                    resolve(imgFile);
                };
                xhr.onerror = (e) => {
                    reject(e)
                };
                // 发送
                xhr.send();
            });
        },

        decodeName(name) {
            return name ? decodeURIComponent(name) : '';
        }
    },
    computed: {
        getSlideList() {
            return this.$store.state.slides;
        },
        getPageInfo() {
            if (this.$store.state.activeOption == 'installPage' || this.$store.state.activeOption == 'upgradePage') {
                var pageInfo = this.$store.state.productInfo[this.$store.state.activeOption].pages.page[this.$store.state.activePageIndex];
                return pageInfo;

            } else
                return {
                    pageName: '',
                    pageType: '',
                    backgroundImage: {},
                    license: {}
                };
        },
        getBgImgName() {
            return decodeURIComponent(this.getPageInfo.backgroundImage.name);
        },
        getInputAccept() {
            if (!this.$store.state.productInfo[this.$store.state.activeOption]) return '';
            if (this.$store.state.productInfo[this.$store.state.activeOption].pages.page[this.$store.state.activePageIndex].pageType == 1) {
                return 'image/png,image/jpeg';
            } else {
                return 'image/bmp';
            }

        },
        downloadURL() {
            var action = this.getAction(this.$store.state.activePageIndex, this.$store.state.activeOption);
            var fileUrl = this.getPageInfo.backgroundImage.url;
            var filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length);
            //alert(filename);
            return '/magicflu/service/s/' + this.$store.state.spaceId + '/packageres/' + this.$store.state.productInfo.id + '/' + action + '/' + filename;
        },
        getBackGroundImageURL() {
            return this.getPageInfo.backgroundImage.url + '?t=' + new Date().getTime();
        },
        stayTime: {
            get() {
                return this.getPageInfo.stayTime;
            },
            set(value) {
                this.$store.commit('updateStayTime', value);
            }
        },
        pageName: {
            get() {
                return this.getPageInfo.pageName;
            },
            set(value) {
                this.$store.commit('updatePageName', value);
            }
        }
    }
}
</script>
<style>
/*页面设置*/
#pageSet {
    width: 460px;
    height: 550px;
    border: 1px solid #a8a8a8;
    background: #f8f8f8;
    border-radius: 4px;
    overflow: hidden;
    padding: 0px 20px;
}

#pageSet>div.nameBox {
    padding: 20px 0px;
}

#pageSet>p.attrTitle {
    margin: 20px 0 10px;
}

#pageSet>p.attrTitle>a {
    font-size: 12px;
    font-weight: normal;
    font-stretch: normal;
    color: #57a8ff;
}

#pageSet>div.imgBox {
    overflow: hidden;
}

#pageSet>div.imgBox>p {
    float: left;
}

#pageSet>div.imgBox>p>img {
    width: 260px;
    height: 195px;
    background-color: #ffffff;
    border-radius: 4px;
    border: solid 1px #666666;
}

#pageSet>div.imgBox>p>span.fileName {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 260px;
}

#pageSet>div.licenseBox {
    margin-top: 20px;
}

#pageSet>div.licenseBox>p {
    height: 40px;
}

#pageSet>div.licenseBox>span.tagspan {
    color: #57a8ff;
    font-size: 12px;
    display: block;
    margin-top: 5px;
}

#pageSet>div.licenseBox>span.filespan {
    color: #929090;
    display: block;
}

#pageSet>div.imgBox>p>span.greyBtn,
#pageSet>div.licenseBox>p>span.greyBtn {
    background-color: #666666;
    border-radius: 4px;
    font-size: 16px;
    font-weight: normal;
    font-stretch: normal;
    color: #ffffff;
    display: inline-block;
    margin-bottom: 28px;
    margin-left: 20px;
    width: 100px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    position: relative;
}

#pageSet .textInput {
    width: 260px;
    height: 30px;
    background-color: #ffffff;
    border-radius: 4px;
    border: solid 1px #666666;
    margin-top: 10px;
}

#pageSet .slideTimeBox {
    margin-top: 20px;
}

span.greyBtn>input {
    width: 100%;
    height: 100%;
    opacity: 0;
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
}

.a_download {
    TEXT-DECORATION: none;
    color: #fff;
    width: 100px;
    height: 35px;
    display: block;
    margin-left: 20px;
    margin-bottom: 28px;
    background-color: #666666;
    border-radius: 4px;
    font-size: 16px;
    font-weight: normal;
    font-stretch: normal;
    line-height: 35px;
    text-align: center;
    cursor: pointer;
}

.myTip {
    position: relative;
    vertical-align: middle;
    cursor: pointer;
}

.myTip span.myText {
    position: absolute;
    top: -10px;
    left: 30px;
    width: 230px;
    font-size: 12px;
    color: rgb(255, 111, 111);
    line-height: 16px;
    text-align: left;
    z-index: 100;
    border-width: 1px;
    border-style: solid;
    border-color: rgb(168, 168, 168);
    border-image: initial;
    background: rgb(255, 255, 225);
    padding: 5px 6px;
    border-radius: 4px;
}

.myTip span.myText>img {
    position: absolute;
    top: 8px;
    left: -9px;
}

#slideListDiv {
    text-align: center;
    height: 500px;
    width: 980px;
    overflow: auto;
}

#slideListUL {
    width: 95%;
    height: 99%;
    text-align: center;
    display: inline-block;
}

#slideListUL li {
    width: 280px;
    height: 188px;
    background-color: #ffffff;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    border: solid 1px #e0e0e0;
    float: left;
    margin: 20px 20px 20px 0;
    list-style: none;
    display: inline;
}

div.slideDiv {
    float: left;
    overflow: hidden;
    border-radius: 4px 4px 0 0;
    height: 188px;
}

div.slideDiv:hover {
    cursor: pointer;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.1);
}

.slideDivActive {
    border: solid 2px #2098ce;
}

div.slideDiv>img {
    width: 280px;
    height: 188px;

}

@media screen and (max-width: 1023px) {
    #pageSet {
        width: 390px;
        height: 500px;
    }

    #pageSet>p.attrTitle {
        margin: 20px 0 10px;
    }

    #pageSet>div.licenseBox {
        margin-top: 20px;
    }
}

@media screen and (min-width:1024px) and (max-width: 1365px) {
    #pageSet {
        width: 390px;
        height: 500px;
    }

    #pageSet>p.attrTitle {
        margin: 20px 0 10px;
    }

    #pageSet>div.licenseBox {
        margin-top: 20px;
    }

    #slideListDiv {
        text-align: center;
        height: 400px;
        width: 980px;
        overflow: auto;
    }
}

@media screen and (min-width:1366px) and (max-width: 1439px) {
    #pageSet {
        width: 390px;
        height: 450px;
    }

    #pageSet>p.attrTitle {
        margin: 0px 0 10px;
    }

    #pageSet>div.licenseBox {
        margin-top: 0px;
    }

    #slideListDiv {
        text-align: center;
        height: 400px;
        width: 980px;
        overflow: auto;
    }
}

@media screen and (min-width:1440px) and (max-width:1599px) {
    #pageSet {
        width: 400px;
        height: 480px;
    }

    #pageSet>p.attrTitle {
        margin: 10px 0 10px;
    }

    #pageSet>div.licenseBox {
        margin-top: 20px;
    }

    #slideListDiv {
        text-align: center;
        height: 400px;
        width: 980px;
        overflow: auto;
    }

}

@media screen and (min-width:1600px) and (max-width:1919px) {
    #pageSet {
        width: 410px;
        height: 500px;
    }

    #pageSet>p.attrTitle {
        margin: 20px 0 10px;
    }

    #pageSet>div.licenseBox {
        margin-top: 20px;
    }

    #slideListDiv {
        text-align: center;
        height: 600px;
        width: 980px;
        overflow: auto;
    }
}
</style>

